package mything;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TestJDBC {
    public static void main(String[] args) {
//        Configuration configuration = new Configuration();
//        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
//        try (SqlSession session = sessionFactory.openSession()){
        findStudent();
    }

    private static void findStudent() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try{
// 1. 注册 MySQL 驱动
//            Class.forName("com.mysql.jdbc.Driver");
            String driver = "com.mysql.jdbc.Driver";
            Class.forName(driver);
// 2. 创建连接对象：连接数据的基本信息 url，username，password
            String url = "jdbc:mysql://localhost:3306/py-school-db";
            String username = "root";
            String password = "root";
            conn = DriverManager.getConnection( url, username, password );
// 3. 保存查询结果
            List<Student> stuList = new ArrayList();
// 4. 创建 Statement，用来执行SQL语句
            stmt = conn.createStatement();
// 5. 执行查询，创建记录集
            String sql = "select * from students";
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                Student stu = new Student();
                stu.setId(rs.getInt("sno"));
                stu.setName(rs.getString("sname"));
//                stu.setAge(rs.getInt("age"));
                System.out.println(stu);
                stuList.add(stu);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try{
// 6. 资源释放
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(conn != null) conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
class Student{
    int id;
    String name;
    int age = 18;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}